import 'dart:async';

// 自定义取消异常类，便于识别取消行为
class CancelledException implements Exception {
  final String message;
  CancelledException([this.message = "Task cancelled"]);

  @override
  String toString() => message;
}

void main() async {
  // 创建一个 Completer
  final completer = Completer<void>();

  // 模拟一个异步任务，它将在2秒后完成Completer
  Future.delayed(Duration(seconds: 2), () {
    // 在完成前检查Completer是否已被取消（已完成）
    if (!completer.isCompleted) {
      completer.complete(); // 正常完成
      print("Task completed normally.");
    }
  });

  // 模拟在1秒后取消任务
  Future.delayed(Duration(seconds: 1), () {
    if (!completer.isCompleted) {
      // 关键：通过发送错误信号来“取消”Completer
      completer.completeError(CancelledException());
      print("Cancellation signal sent.");
    }
  });

  // 处理结果
  try {
    await completer.future;
    print("Future completed successfully.");
  } on CancelledException catch (e) {
    print("Caught CancelledException: $e");
  } catch (e) {
    print("Caught other error: $e");
  }
}